/*
 * Copyright 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package example.springdata.redis.reactive;

import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.redis.connection.stream.StreamOffset.*;

import example.springdata.redis.SensorData;
import reactor.test.StepVerifier;

import java.time.Duration;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration;
import org.springframework.boot.data.redis.test.autoconfigure.DataRedisTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamOffset;
import org.springframework.data.redis.core.ReactiveStreamOperations;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.stream.StreamReceiver;

import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

import com.redis.testcontainers.RedisContainer;

/**
 * @author Christoph Strobl
 */
@Testcontainers
@DataRedisTest
@ImportAutoConfiguration(DataRedisReactiveAutoConfiguration.class)
class ReactiveStreamApiTests {

	@Container
	@ServiceConnection
	static RedisContainer redis = new RedisContainer(DockerImageName.parse("redis:7"));

	@Autowired ReactiveStringRedisTemplate template;
	@Autowired StreamReceiver<String, MapRecord<String, String, String>> streamReceiver;

	private ReactiveStreamOperations<String, String, String> streamOps;

	@BeforeEach
	void setUp() {

		// clear all
		template.getConnectionFactory().getReactiveConnection()
				.serverCommands().flushAll()
				.then().as(StepVerifier::create)
				.verifyComplete();

		streamOps = template.opsForStream();
	}

	@Test
	void basics() {

		// XADD with fixed id
		streamOps.add(SensorData.RECORD_1234_0)
				.as(StepVerifier::create)
				.expectNext(SensorData.RECORD_1234_0.getId()).verifyComplete();

		streamOps.add(SensorData.RECORD_1234_1)
				.as(StepVerifier::create)
				.expectNext(SensorData.RECORD_1234_1.getId()).verifyComplete();

		// XLEN
		streamOps.size(SensorData.KEY)
				.as(StepVerifier::create)
				.expectNext(2L).verifyComplete();

		// XADD errors when timestamp is less than the last inserted
		streamOps.add(SensorData.create("1234", "19.8", "invalid").withId(RecordId.of("0-0")))
				.as(StepVerifier::create)
				.verifyError(RedisSystemException.class);

		// XADD with autogenerated id
		streamOps.add(SensorData.create("1234", "19.8", null))
				.as(StepVerifier::create)
				.consumeNextWith(autogeneratedId -> autogeneratedId.getValue().endsWith("-0")).verifyComplete();

		streamOps.size(SensorData.KEY)
				.as(StepVerifier::create)
				.expectNext(3L).verifyComplete();

		// XREAD from start
		streamOps.read(fromStart(SensorData.KEY))
				.map(MapRecord::getId)
				.as(StepVerifier::create)
				.expectNext(SensorData.RECORD_1234_0.getId(), SensorData.RECORD_1234_1.getId())
				.expectNextCount(1).verifyComplete();

		// XREAD resume after
		streamOps.read(StreamOffset.create(SensorData.KEY, ReadOffset.from(SensorData.RECORD_1234_1.getId())))
				.as(StepVerifier::create)
				.expectNextCount(1).verifyComplete();
	}

	@Test
	void continuousRead() {

		var messages = streamReceiver.receive(fromStart(SensorData.KEY));

		messages.as(StepVerifier::create)
				.then(() ->
						streamOps.add(SensorData.RECORD_1234_0)
								.then(streamOps.add(SensorData.RECORD_1234_1))
								.subscribe())
				.consumeNextWith(it -> {
					assertThat(it.getId()).isEqualTo(SensorData.RECORD_1234_0.getId());
				})
				.consumeNextWith(it -> {
					assertThat(it.getId()).isEqualTo(SensorData.RECORD_1234_1.getId());
				})
				.then(() -> streamOps.add(SensorData.RECORD_1235_0)
						.subscribe())
				.consumeNextWith(it -> {
					assertThat(it.getId()).isEqualTo(SensorData.RECORD_1235_0.getId());
				})
				.thenCancel()
				.verify(Duration.ofSeconds(5));
	}
}
